<?php

	/*
	 * 
	 * File Name: index.php
	 * Author: Matthew Watts {http://euphoriccode.com}
	 * Version: 1.0.0
    *
	 */

	#	We need a version
	define('VERSION', '1.0.0');
	
	#	Time for some configuration
	require_once 'config.php';
	
	#	Moving on to the installation detection
	
	#	What we are doing here is checking to see if this is a new installation
	#	and if it is not we are going to redirect the application to the installation 
	#	directory so that we can commence with a fresh install. 
	if (!defined('DIR_APPLICATION'))	{
		header('Location: install/index.php');
		exit;
	}
	
	#	Starting up the engines
	require_once (DIR_SYSTEM. 'startup.php');
	
	#	Now we need to load our application classes
	require_once (DIR_SYSTEM . 'library/customer.php');
	require_once (DIR_SYSTEM . 'library/affiliate.php');
	require_once (DIR_SYSTEM . 'library/currency.php');
	require_once (DIR_SYSTEM . 'library/tax.php');
	require_once (DIR_SYSTEM . 'library/weight.php');
	require_once (DIR_SYSTEM . 'library/length.php');
	require_once (DIR_SYSTEM . 'library/cart.php');
	
	#	Registry Time
	$registry = new Registry();
	
	#	Loader Time
	$loader = new Loader($registry);
	$registry ->set('load', $loader);
	
	#	A Little Configuration 
	$config = new Config();
	$registry->set('config', $config);
	
	#	Now the good old database
	$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
	$registry->set('db', $db);
	
	#	And now for the store
	if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
	$store_query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`ssl`, 'www.', '') = '" . $db->escape('https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
	} else {
		$store_query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`url`, 'www.', '') = '" . $db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
	}
	
	if ($store_query->num_rows)	{
		$config->set('config_store_id', $store_query->row['store_id']);
	}	else 	{
		$config->set('config_store_id', 0);
	}
	
	#	Settings Time
	$query = $db->query*("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '0' OR store_id = '" . (int) $config->get('config_store_id') . "' ORDER BY store_id ASC");
	
	foreach ($query->rows as  $setting)	{
		$config->set($setting['key'], $setting['value']);
	}
	
	if (!$store_query->num_rows)	{
		$config->set('config_url', HTTP_SERVER);
		$config->set('config_ssl', HTTPS_SERVER);
	}
	
	#	Now for the URL
	$url = new Url($config->get('config_url'), $config->get('config_ssl'));
	$registry->set('url', $url);
	
	#	Commencing the logs
	$log = new Log($config->get('config_error_filename'));
	$registry->set('log', $log);
	
	#	Setting up the function. Sexy time!
	function error_handler($errno, $errstr, $errfile, $errline)	{
		global $log, $config;
		
		switch ($errno)	{
			case E_NOTICE:
			case E_USER_NOTICE:
				$error = 'Notice';
				break;
				
			case E_WARNING:
			case E_USER_WARNING:
				$error = 'Warning';
				break;
				
			case E_ERROR:
			case E_USER_ERROR:
				$error = 'Fatal Error';
				break;
				
			default:
				$error = 'Unknown';
				break;
				
		}
		
		if ($config->get('config_error_display'))	{
			echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
		}
		
		if ($config->get('config_error_log'))	{
			$log->write('PHP ' . $error . ': ' . $errstr. ' in ' . $errfile . ' on line '. $errline);
		}
		return true;
	}
	
	#	Now for the error handler
	set_error_handler('error_handler');
	
	#	Now for the requests
	$request = new Request();
	$registry->set('request', $request);
	
	#	Time for a response
	$response = new Response();
	$response->addHeader('Content-Type: text/html; charset=utf-8');
	$response->setCompression($config->get('config_compression'));
	$registry->set('response', $response);
	
	#	Cache Time
	$cache = new Cache();
	$registry->set('cache', $cache);
	
	#	Now for the session 
	$session = new Session();
	$registry->set('session', $session);
	
	#	Now for a little juicy language detection
	$language = array();
	$query = $db->query("SELECT * FROM " . DB_PREFIX . "language");
	foreach ($query->rows as $result)	{
		$languages[$result['code']] = $result;
	}
	
	$detect = '';
	
	if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) && ($request->server['HTTP_ACCEPT_LANGUAGE']))	{
		$browser_languages = explode(',', $request->server["HTTP_ACCEPT_LANGUAGE"]);
		
		foreach ($browser_languages as $browser_language)	{
			foreach ($languages as $key => $value)	{
				if ($value['status'])	{
					$locale = explode(',', $value['locale']);
					
					if (in_array($browser_language, $locale))	{
						$detect = $key;
					}
				}
			}
		}
	}
	
	if (isset($request->get['language']) && array_key_exists($request->get['language'], $languages) && $languages [$request->get['language']]['status'])	{
		$code = $request->get['language'];
	}	elseif (isset($session->data['language']) && array_key_exists($session->data['language'], $languages))	{
		$code = $session->data['language'];
	}	elseif (isset($request->cookie['language']) && array_key_exists($request->cookie['language'], $languages))	{
		$code = $request->cookie['language'];	
	}	elseif ($detect)	{
		$code = $detect;
	}	else 	{
		$code = $config->get('config_language');
	}
	
	if (!isset($session->data['language']) || $session->data['language'] != $code)	{
		$session->data['language'] = $code;
	}
	
	if (!isset($request->cookie['language']) || $request->cookie['language'] !=$code)	{
		setcookie('language', $code, time() +60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
	}
	
	$config->set('config_language_id', $languages[$code]['language_id']);
	$config->set('config_language', $languages[$code]['code']);
	
	$language = new Language($languages[$code]['directory']);
	$language->load($languages[$code]['filename']);
	$registry->set('language', $language);
	
	#	Documentation Time
	$document = new Document();
	$registry->set('document', $document);
	
	#	Customers please, and loads of them
	$registry->set('customer', new Customer($registry));
	
	#	Now for the Affiliates
	$affiliate = new Affiliate($registry);
	$registry->set('affiliate', $affiliate);
	
	if (isset($request->get['tracking']) && !isset($request->cookie['tracking']))	{
		setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
	}
	
	#	Now for the currency
	$registry->set('currency', new Currency($registry));
	
	#	Then the tax
	$registry->set('tax', new Tax($registry));
	
	#	Now for the weight
	$registry->set('weight', new Weight($registry));
	
	#	Now for a little length
	$registry->set('length', new Length($registry));
	
	#	Now for the Shpping Cart 
	$registry->set('cart', new cart($registry));
	
	#	Now we need the front controller 
	$controller = new Front($registry);
	
	#	Now For Maintenance Mode
	$controller->addPreAction(new Action('common/maintenance'));
	
	#	A little SEO
	$controller->addPreAction(new Action('common/seo_url'));
	
	#	A little Routing
	if (isset($request->get['route']))	{
		$action = new Action($request->get['route']);
	}	else	{
		$action = new Action('common/home');
	}
	
	#	Now for the dispatch
	$controller->dispatch($action, new Action('error/not_found'));
	
	#	Now a little Output
	$response->output();
	
?>